<script setup lang="ts">
import {
  useMessage,
  NButton,
  NDataTable,
  type DataTableColumns,
  type DataTableRowKey
} from 'naive-ui'
import { onMounted, ref } from 'vue'
import { sendRequest } from '@/utils/api'
import FixedAction from '@/components/FixedAction.vue'
import useRouteReplace from '@/hooks/useRouteReplace'
import useRouteParam from '@/hooks/useRouteParam'
import type { HttpResponse } from '@/utils/http'
import { useRoute } from 'vue-router'

const route = useRoute()
const routeReplace = useRouteReplace(route.query.redirect as string)
const message = useMessage()
useRouteParam('id', () => queryRoleInfo())

const checkedKeys = ref<number[]>([])

const columns: DataTableColumns = [
  {
    type: 'selection'
  },
  {
    title: '角色名称',
    key: 'roleName',
    align: 'center'
  },
  {
    title: '备注',
    key: 'notes',
    align: 'center'
  }
]

const tableData = ref<any[]>([])
const tableLoading = ref(false)
const queryTableData = async () => {
  tableLoading.value = true
  const [error, res] = await sendRequest<HttpResponse>({
    module: 'role',
    api: 'selectFilter'
  })
  tableLoading.value = false

  if (error) return message.error(error.message)
  tableData.value = res.data
}

const submitLoading = ref(false)
const handleCheck = (e: DataTableRowKey[]) => {
  checkedKeys.value = e as number[]
}

const handleSubmit = async () => {
  try {
    submitLoading.value = true
    const [error, res] = await sendRequest<HttpResponse>({
      module: 'user',
      api: 'updateUserRole',
      override: {
        data: {
          roleIdList: checkedKeys.value.filter((e) => tableData.value.some((c) => c.id === e)),
          userId: route.params.id as string
        }
      }
    })
    if (error) return message.error(error.message)
    if (res.code !== 0) return message.error(res.msg)
    message.success(res.msg)
    window.flags.flushUserPermission = true
    routeReplace()
  } catch (error) {
    console.log(error)
  } finally {
    submitLoading.value = false
  }
}

const queryRoleInfo = async () => {
  try {
    const [error, res] = await sendRequest({
      module: 'role',
      api: 'bindingList',
      override: {
        params: {
          userId: route.params.id as string,
          limit: 100000,
          page: 1
        }
      }
    })
    if (error) throw error
    if (res.code !== 0) throw new Error(res.msg)
    checkedKeys.value = res.data
  } catch (error: any) {
    message.error(error.message)
  }
}

onMounted(() => {
  queryTableData()
  queryRoleInfo()
})
</script>

<template>
  <div class="bind-permission">
    <NDataTable
      style="flex: 1"
      :loading="tableLoading"
      :columns="columns"
      :data="tableData"
      selection
      :row-key="(e) => e.id"
      :checked-row-keys="checkedKeys"
      @update:checked-row-keys="handleCheck"
      flex-height
    />
  </div>

  <FixedAction>
    <div class="bind-permission-buttons">
      <NButton
        color="#999999"
        ghost
        :disabled="submitLoading"
        @click="routeReplace"
      >
        取消
      </NButton>

      <NButton
        color="#5FB17F"
        :disabled="submitLoading"
        :loading="submitLoading"
        @click="handleSubmit"
      >
        确定
      </NButton>
    </div>
  </FixedAction>
</template>

<style scoped lang="scss">
.bind-permission {
  height: 100%;
  display: flex;
  flex-direction: column;
  padding: 25rem 56rem 110rem 36rem;
}

.bind-permission-buttons {
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 0 16rem;

  .n-button {
    width: 100rem;
    height: 50rem;
  }
}
</style>
